<%--
  Created by IntelliJ IDEA.
  User: shen
  Date: 2020/5/11
  Time: 16:00
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%
    String path = request.getContextPath();
    String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<html>
<head>
    <base href="<%=basePath%>">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>在线测试</title>
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <%@include file="../common_resource.jsp" %>
    <script type="text/javascript" src="js/wangEditor.min.js"></script>
    <style>
        img[src=""],img:not([src]){
            opacity:0;
        }
    </style>
    <style type="text/css">
        a:hover {color: red; text-decoration:none;}
        .main_body{
            /*position: relative;
            top:190px;*/
            font-size: 14px;
        }
        .table{
            font-size: 14px;
        }
        .w-e-text{
            height: 150px;
        }
        .toolbar {
            border: 1px solid #ccc;
        }
        .text {
            border: 1px solid #ccc;
            height: 400px;
        }
    </style>
    <script>


        function to(){
            location.href="views/question/single_input.jsp";
        }
        function checkAll(){
            var box=document.getElementsByName("selectID");
            var chkall=document.getElementById("checkall");
            if(chkall.checked){
                for(var i=0;i<box.length;i++){
                    box[i].checked=true;
                }
            }else{
                for(var i=0;i<box.length;i++){
                    box[i].checked=false;
                }
            }
        }
        function detail(id){
            var o = document.getElementById("option"+id);
            if (o){
                if (o.style.display == "none"){ o.style.display = "block"; } else {o.style.display = "none";}
            }


            $.get("question/selectQuestionById.do",{"id":id},function(json){
                $.each(json, function(i,item){
                    $("#optionA"+id).html(item.optionA);
                    $("#optionB"+id).html(item.optionB);
                    $("#optionC"+id).html(item.optionC);
                    $("#optionD"+id).html(item.optionD);
                });

            });
        }


        function collapseExpand(ss){
            $(ss).style.display = "block";
        }


        function openOption(){
            var obj=document.getElementsByName('selectID');
            for(var i=0; i<obj.length; i++){
                var id=obj[i].value;
                $.get("question/selectQuestionById.do",{"id":id},function(json){
                    $.each(json, function(i,item){
                        $("#optionA"+item.questionId).html(item.optionA);
                        $("#optionB"+item.questionId).html(item.optionB);
                        $("#optionC"+item.questionId).html(item.optionC);
                        $("#optionD"+item.questionId).html(item.optionD);
                        $("#optionE"+item.questionId).html(item.optionE);
                    });
                });
                var o = document.getElementById("option"+id);
                if (o){
                    if (o.style.display == "none"){ o.style.display = "block";$("#openlog").html("[-]"); } else {o.style.display = "none"; $("#openlog").html("[+]");}
                }
            }

        }
        $(function(){
            <c:if test="${not empty updateRdiolag and updateRdiolag}">
            $("#successModal").modal();
            </c:if>

            <c:if test="${not empty updateRdiolag and (not updateRdiolag)}">
            $("#feildModal").modal();
            </c:if>

            <c:if test="${not empty savaRdiolag and savaRdiolag}">
            $("#insertSuccessModal").modal();
            </c:if>

            <c:if test="${not empty savaRdiolag and (not savaRdiolag)}">
            $("#insertFailModal").modal();
            </c:if>
        });
    </script>

</head>
<body class="main_body">
<div class="container container-1180" >
    <div class="col" style="margin-top: 10px;">
        <div class="panel panel-info">
            <div class="panel-heading">
                <span ><i class="fa fa-user"></i></span> <label><font style="font-weight: bold;margin-left: 10px;">在线测试</font></label>
                <label style="float: right;">
                    <div class="button_bar">
                        <button class="btn btn-info btn-sm" id="submitExam" >提交试卷</button>
<%--
                        <button class="btn btn-info btn-sm" onclick="to()">试卷下载</button>
--%>
                    </div>
                </label>
            </div>
            <form id="searchForm" name="searchForm" role="form"   action="testPaper/test" method="post">
                <!-- 试题类型 -->
                <!-- 查询 -->
                <input type="hidden" name="coll_exp" value="0" />
                <table border="0" width="100%" >

                    <tr>
                        <td >
                            <!-- 列表 -->
                            <div class="listDiv" id="allExam">
                                <c:forEach var="rUnit" items="${sessionScope.resultUnit}" varStatus="status">
                                    <div class="paner-body panel-heading tempExam" >
                                        <label style="color: black;">&nbsp;</label>

                                        <a id="resultUnit" href="">试卷编号：${rUnit.eId}&nbsp;&nbsp;&nbsp;试卷总分：${rUnit.totalScore}&nbsp;&nbsp;&nbsp;试卷难度：${rUnit.difficultyLevel}</a>
                                    </div>
                                </c:forEach>

                                    <%--设置变量--%>
                                    <c:set var="index" value="${1}"/>
                                    <%--单选题--%>
                                <c:forEach var="sQlist" items="${sessionScope.sExamDetail}" varStatus="status">
                                        <c:if test="${sQlist.sdfsQuestions.questionType ==1}">
                                    <label style="color: black;font-size: 15px">单选题：&nbsp;</label>
                                    <div id="question${sQlist.sQuestionID }" class="panel panel-info sExamList" style="font-size: 14px;">
                                    <div class="paner-body panel-heading" >
                                        <label style="color: black;">&nbsp;</label>

                                        ${index}.<a href="javascript:detail(${sQlist.sQuestionID });">${sQlist.sdfsQuestions.question }(2分)</a>
                                    </div>
                                    <div id="option${sQlist.sQuestionID}" class="radio_list_options panel-collapse collapse" style="display: inline-block">
                                        <ul style="margin-left:7px;">
                                            <li><input type="radio" name="sCorrect${sQlist.sQuestionID}" id="optionA${sQlist.sQuestionID}" value="A" required="true">${sQlist.optionA}</li>
                                            <li><input type="radio"  name="sCorrect${sQlist.sQuestionID}"id="optionB${sQlist.sQuestionID}" value="B" required="true">${sQlist.optionB}</li>
                                            <li><input type="radio"  name="sCorrect${sQlist.sQuestionID}"id="optionC${sQlist.sQuestionID}" value="C" required="true">${sQlist.optionC}</li>
                                            <li><input type="radio"  name="sCorrect${sQlist.sQuestionID}"id="optionD${sQlist.sQuestionID}" value="D" required="true">${sQlist.optionD}</li>
                                            <c:if test="${not empty sQlist.optionE}">
                                                <li><input type="radio" id="optionE${sQlist.sQuestionID}" value="E" required="true">${sQlist.optionE}</li>
                                            </c:if>
                                        </ul>
                                    </div>
                                </div>

                                     <div style="height: 10px"></div>
                                    </c:if>
                                        <c:set var="index" value="${index+1}"/>
                                </c:forEach>

                                    <%--设置变量--%>
                                    <c:set var="index" value="${1}"/>
                                    <%--判断题--%>
                                <c:forEach var="dQlist" items="${sessionScope.dExamDetail}" >
                                    <c:if test="${dQlist.sdfsQuestions.questionType ==2}">
                                    <label style="color: black;font-size: 15px">判断题：&nbsp;</label>

                                    <div id="question${dQlist.dQuestionID }" class="panel panel-info dExamList" style="font-size: 14px;">
                                    <div class="paner-body panel-heading">
                                        <label style="color: black;">&nbsp;</label>
                                            ${index}.<a href="javascript:detail(${dQlist.dQuestionID });">${dQlist.sdfsQuestions.question }(2分)</a>
                                    </div>
                                    <div id="option${dQlist.dQuestionID}" class="radio_list_options panel-collapse collapse" style="display: inline-block">
                                        <ul style="margin-left:7px;">
                                            <li><input type="radio" name="dCorrect${dQlist.dQuestionID}" id="T${dQlist.dQuestionID}" value="T" required="ture">T</li>
                                            <li><input type="radio" name="dCorrect${dQlist.dQuestionID}"id="F${dQlist.dQuestionID}" value="F" required="true">F</li>
                                        </ul>

                                        <input type="hidden" name="fCorrect" value="${dQlist.dCorrect}">
                                    </div>
                                </div>
                                    <div style="height: 10px"></div>
                                    </c:if>
                                    <c:set var="index" value="${index+1}"/>
                                </c:forEach>

                                    <%--设置变量--%>
                                    <c:set var="index" value="${1}"/>
                                    <%--填空题--%>
                                    <c:forEach var="fQlist" items="${sessionScope.fExamDetail}" varStatus="status">
                                         <c:if test="${fQlist.sdfsQuestions.questionType ==3}">
                                    <label style="color: black;font-size: 15px">填空题：&nbsp;</label>

                                    <div id="question${fQlist.fQuestionID }" class="panel panel-info fExamList" style="font-size: 14px;">
                                        <div class="paner-body panel-heading" >
                                            <label style="color: black;">&nbsp;</label>
                                                ${index}.<a style="" href="javascript:detail(${fQlist.fQuestionID });">${fQlist.sdfsQuestions.question }(2分)
<%--
                                                            <span onclick="detail(${fQlist.fQuestionID })" style="size: A4">&nbsp;&nbsp;展开[+]</span>
--%>
                                                         </a>
                                        </div>

                                        <div id="option${fQlist.fQuestionID}" class="file-list panel-collapse collapse" style="display: inline-block">
                                           <%-- <div class="answer" id="answer${fQlist.fQuestionID }" name="answer" style="height: 150px">

                                            </div>--%>
                                               <textarea name="fAnswer" cols="113" rows="5" class="easyui-validatebox form-control fAnswer"  required="true" style="width: 500px;margin-bottom: 0px" placeholder="请输入填空题的答案......"></textarea>
                                               <a href="javascript:void(0)" onclick="uploadPhoto('${fQlist.fQuestionID}')" >选择上传答案的图片</a>
                                               <input type="file" id="photoFile${fQlist.fQuestionID}" style="display: none;" onchange="upload('${fQlist.fQuestionID}')">
                                               <img id="preview_photo${fQlist.fQuestionID}" class="preview_photo">

                                            <input type="hidden" name="fCorrect" value="${fQlist.fCorrect}">
                                        </div>
                                    </div>
                                    <span style="margin-left:20px;">
<%--
                                                <input type="button" class="btn btn-info btn-sm" data-backdrop="static" value="保存" onclick="doAdd(${fQlist.fQuestionID});"></input>
--%>
                                    </span>
                                        <div style="height: 10px"></div>
                                    </c:if>
                                    <c:set var="index" value="${index+1}"/>
                                    </c:forEach>

                                    <%--设置变量--%>
                                    <c:set var="index" value="${1}"/>
                                    <c:forEach var="shQlist" items="${sessionScope.shExamDetail}" >

                                    <c:if test="${shQlist.sdfsQuestions.questionType ==4 or shQlist.sdfsQuestions.questionType ==5}">
                                         <label style="color: black;font-size: 15px">简答综合题：&nbsp;</label>

                                    <div id="question${shQlist.shQuestionID }" class="panel panel-info shExamList" style="font-size: 14px;">
                                            <div class="paner-body panel-heading" >
                                            <label style="color: black;">&nbsp;</label>
                                             ${index}.<a id="questionBody" style="" href="javascript:detail(${shQlist.shQuestionID});">${shQlist.sdfsQuestions.question}(5分)
<%--
                                                <span onclick="detail(${shQlist.shQuestionID})" style="size: A4">展开[+]</span>
--%>

                                            </a>
                                                <img id="images" alt="" src="images/upload/${shQlist.shQuestionImage}">

                                            </div>
                                        <br/>
                                        <div id="option${shQlist.shQuestionID}" class="panel-collapse collapse" style="display: inline-block">
                                            <%--<div class="answer" id="answer${shQlist.shQuestionID }" name="answer" style="height: 150px">

                                            </div>--%>
                                         <textarea name="shAnswer" cols="113" rows="5" class="easyui-validatebox form-control shAnswer"  required="true" style="width: 500px;margin-bottom: 0px" placeholder="请输入简答题的答案......"></textarea>
                                                <a href="javascript:void(0)" onclick="uploadPhoto('${shQlist.shQuestionID}')" >选择上传答案的图片</a>
                                                <input type="file" id="photoFile${shQlist.shQuestionID}" style="display: none;" onchange="upload('${shQlist.shQuestionID}')">
                                                <img id="preview_photo${shQlist.shQuestionID}" class="preview_photo">

                                      </div>
                                    </div>
                                        <div style="height: 10px"></div>
                                    </c:if>
                                    <c:set var="index" value="${index+1}"/>
                                    </c:forEach>
                        </td>
                    </tr>
                </table>

            </form>
        </div>
    </div>
</div>


<script src="bootstrap/plugins/modal.js"></script>
<script src="bootstrap/plugins/collapse.js"></script>
<script src="bootstrap/js/jquery.editable-select.min.js"></script>
<script src="js/jquery-2.0.0.js"></script>
<script src="bootstrap/js/bootstrap.js"></script>

<script>
    function uploadPhoto(qId) {
        $("#photoFile"+qId).click();
    }

    /**
     * 上传图片
     */
    function upload(qId) {
        if ($("#photoFile"+qId).val() == '') {
            return;
        }
        var formData = new FormData();
        formData.append('photo', document.getElementById('photoFile'+qId).files[0]);
        $.ajax({
            url:"${pageContext.request.contextPath}/editor/uploadPhoto",
            type:"post",
            data: formData,
            contentType: false,
            processData: false,
            success: function(data) {
                if (data.type == "success") {
                    $("#preview_photo"+qId).attr("src", data.filepath+data.filename);
                    $("#productImg"+qId).val(data.filename);
                } else {
                    alert(data.msg);
                }
            },
            error:function(data) {
                alert("上传失败")
            }
        });
    }
</script>
<script>

    function gosubmit(){
        var formdata=new FormData();
        //formdata.append('name', 'uploadImage');
        formdata.append('uploadImage',$('#uploadImage').get(0).files[0]);
        formdata.append('recid',str);
        $.ajax({
            url:'dy_upload_image.jspx',
            type:'post',
            contentType:false,
            data:formdata,
            processData:false,
            success:function(info){
                console.log(info)
                $('.backimg').attr('src',JSON.parse(info).msg);
            },
            error:function(err){
                console.log(err)
            }
        });
    }
   /* $(function () {
        data(){
            return {
                editContent:''//存储富文本编辑器的内容
            }
        },


        methods:{
            wangEdit (id) {
                let editor = new E(id)
                editor.customConfig.onchange = (html) => {
                    this.editContent = html//动态获取富文本编辑器的内容
                }
                editor.customConfig.uploadImgMaxSize = 3 * 1024 * 1024;
                editor.customConfig.uploadFileName = 'file[]'
                editor.customConfig.uploadImgServer = '/proxy/platform/photo.moreImgUpload'//换成后端给你的上传图片的接口
                editor.customConfig.uploadImgHooks = {
                    before: function (xhr, editor, files) {
                        let formdata=new FormData();
                        for(let i=0;i<files.length;i++){
                            let url = files[i];
                            formdata.append('file[]', url)
                        }
                    },
                    customInsert: function (insertImg, result, editor) {
                        for(let i=0;i<result.data.length;i++){
                            let url = result.data[i]
                            insertImg(url)
                        }
                    }
                }
                editor.create()
            }
        }


//使用：this.wangEdit(‘#edit’)
    })*/

    function detail(qId) {

            //var fExamList = $('.fExamList');
            // $('.fExamList> answer').each(function (index,domfile) {
        var aQid = $('#answer'+qId);
        var w = $('.w-e-toolbar');

        //console.log(aQid.contains(w))
        if(aQid.find("div").length==0){

            var E = window.wangEditor;

            var editor = new E('#answer'+qId);

            editor.customConfig.uploadImgServer = 'editor/upload'; //上传URL
            editor.customConfig.uploadImgMaxSize = 3 * 1024 * 1024;
            editor.customConfig.uploadImgMaxLength = 5;
            editor.customConfig.uploadFileName = 'myFileName';
            editor.customConfig.uploadImgHooks = {
                before: function (xhr, editor, files) {
                    // 图片上传之前触发
                    // xhr 是 XMLHttpRequst 对象，editor 是编辑器对象，files 是选择的图片文件

                    // 如果返回的结果是 {prevent: true, msg: 'xxxx'} 则表示用户放弃上传
                    // return {
                    //     prevent: true,
                    //     msg: '放弃上传'
                    // }
                },
               /* success: function (xhr, editor, result) {
                    // 图片上传并返回结果，图片插入成功之后触发
                    // xhr 是 XMLHttpRequst 对象，editor 是编辑器对象，result 是服务器端返回的结果
                    alert('插入图片成功' )

                },
*/
                error: function (xhr, editor) {
                    // 图片上传出错时触发
                    // xhr 是 XMLHttpRequst 对象，editor 是编辑器对象
                    alert('上传图片失败：' + result)

                },
                timeout: function (xhr, editor) {
                    // 图片上传超时时触发
                    // xhr 是 XMLHttpRequst 对象，editor 是编辑器对象
                },

                /* before: function (xhr, editor, files) {
                     var formdata=new FormData();
                     for(var i=0;i<files.length;i++){
                         var url = files[i];
                         formdata.append('file[]', url)
                     }
                     console.log(formdata)
                 },*/
                customInsert: function (insertImg, result, editor) {

                    // 图片上传并返回结果，自定义插入图片的事件（而不是编辑器自动插入图片！！！）
                    // insertImg 是插入图片的函数，editor 是编辑器对象，result 是服务器端返回的结果
                    // 举例：假如上传图片成功后，服务器端返回的是 {url:'....'} 这种格式，即可这样插入图片：
                    for(var i=0;i<result.data.length;i++){
                        var url = result.data;
                        insertImg(url);
                    }
                    alert('上传图片成功')

                    console.log("成功")
                    // result 必须是一个 JSON 格式字符串！！！否则报错
                }
            }
            editor.customConfig.customAlert = function (info) {
                // info 是需要提示的内容
                alert('插入图片成功')
            }

            editor.create();
            // })
        }

    }

function doAdd(qId) {


}
/*
var $text1 = $("#text1");
        添加onchange事件实现textarea提交
   editor.customConfig.onchange = function (html) {
       // 监控变化，同步更新到 textarea
       $text1.val(html)
   }
*/

    /*
    * //自己定义上传的方法
    *
    *
            editor.customConfig.customUploadImg = function (files, insert) {
                var daw = new FormData();
                for(var i=0;i<files.length;i++){
                    daw.append("files",files[i]);
                }
                index = layer.load(1, {
                    shade: [0.1,'#fff'] //0.1透明度的白色背景
                });

                $.ajax({
                    url:'editor/wangEditUploadImag',
                    type: "POST",
                    data: daw,
                    async: false,
                    cache: false,
                    contentType: false,
                    processData: false,
                    success:function(da){
                        layer.close(index);
                        if(da.errno == 0){
                            for(var j=0;j<da.data.length;j++){
                                insert(da.data[j]);
                                console.log(123)
                            }
                        }else{
                            alert(da.msg);
                            return;
                        }
                    }
                });
            }

            editor.create();

    * */
</script>


<script>
    $(function () {
        // Set数据结构存放所有题型信息
        sExamListAnswer = new Array();
        dExamListAnswer = new Array();
        fExamListAnswer = new Array();
        shExamListAnswer = new Array();
        fExamImages = new Array();
        shExamImages = new Array();
        //存放传给后台的所有数据
        resultMap={};

        $("#submitExam").click(function(){
            if(confirm("确定要提交试卷吗？")){
                //点击确定按钮
                submitExamClick();
            }
        })
    })
    // 点击提交试卷按钮，封装所有数据
    function submitExamClick() {

        var sExamList = $('.sExamList');
        var dExamList = $('.dExamList');
        var fExamList = $('.fExamList');
        var shExamList = $('.shExamList');
        // 先清空
        sExamListAnswer = [];
        dExamListAnswer = [];
        fExamListAnswer = [];
        shExamListAnswer = [];
        fExamImages = [];
        shExamImages = [];


        $('.sExamList>div input:radio:checked').each(function (index,domfile) {
            console.log($(domfile).val())
            sExamListAnswer.push($(domfile).val())
        })
        $('.dExamList>div input:radio:checked').each(function (index,domfile) {
            dExamListAnswer.push($(domfile).val())
            console.log($(domfile).val())
        })


        $('.fExamList .fAnswer').each(function (index,domfile) {

            // 获取富文本的html
            var text = $(domfile).val();
            fExamListAnswer.push(text)
            console.log($(domfile).val())
        })

        $('.shExamList .shAnswer').each(function (index,domfile) {
            // 获取富文本的html
            console.log($(domfile))

            shExamListAnswer.push($(domfile).val())
        })

        $('.fExamList .preview_photo').each(function (index,domfile) {
            // 获取富文本的img
            fExamImages.push($(domfile)[0].src)
            console.log($(domfile).src)
        })
        $('.shExamList .preview_photo').each(function (index,domfile) {
            // 获取富文本的html
            shExamImages.push($(domfile)[0].src)
            console.log($(domfile).src)
        })

        resultMap = {};

        resultMap["sExamList"]=sExamListAnswer;
        resultMap["dExamList"]=dExamListAnswer;
        resultMap["fExamList"]=fExamListAnswer;
        resultMap["shExamList"]=shExamListAnswer;
        resultMap["fExamImages"]=fExamImages;
        resultMap["shExamImages"]=shExamImages;

        console.log(sExamListAnswer)

        submitExam();
    }
    function repalceHtml(str){
        str = str.replace(/<[^>]+>|&[^>]+;/g,"").trim();//去掉所有的html标签和&nbsp;之类的特殊符号
        return str;
    }
    // 发送请求到后端处理数据
    function submitExam() {
        var jsonData=JSON.stringify(resultMap);
        console.log(jsonData)

        $.ajax({
            url:'testPaper/insertExam',
            method:'post',
            contentType: "application/json; charset=utf-8",
            data:jsonData,
            success:function(data){
                //alert(data)
                if(data.insertExam!=0){
                        location.reload();
                        //跳转评分页面
                        location.href="views/exam/gradeTest.jsp"
                }
            },
            error:function(){
                alert("error");
            }
        })
    }

</script>
</body>
</html>


